import time
import threading
import logging
from .sip_handler import SipHandler
from .media_handler import MediaHandler
from .command_processor import CommandProcessor
from .device_controller import DeviceController
from .xml_builder import XMLBuilder
from .config import CONFIG

class GB28181Client:
    def __init__(self, config=CONFIG):
        self.config = config
        self.logger = logging.getLogger('GBClient')
        self.running = False
        
        # 初始化模块
        self.device_controller = DeviceController(config)
        self.media_handler = MediaHandler(config['media'])
        self.command_processor = CommandProcessor(
            config, 
            None,  # 将在下面设置
            self.media_handler,
            self.device_controller
        )
        
        self.sip_handler = SipHandler(config, self.command_processor)
        self.command_processor.sip_handler = self.sip_handler
        
    def start(self):
        """启动客户端"""
        self.running = True
        self.logger.info("启动GB28181客户端")
        
        # 注册到SIP服务器
        self.sip_handler.register()
        
        # 启动心跳线程
        heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
        heartbeat_thread.start()
        
        # 主循环
        try:
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            self.stop()
    
    def stop(self):
        """停止客户端"""
        self.logger.info("停止客户端...")
        self.running = False
        self.sip_handler.unregister()
        # 实际实现中需要更完善的清理
    
    def request_live_video(self, channel_id):
        """请求实时视频流"""
        self.logger.info(f"请求实时视频: {channel_id}")
        # 伪代码：实际实现需要启动媒体流处理
        # port = self.media_handler.create_receiver(channel_id)
        # sdp = self._generate_sdp(port)
        # self.sip_handler.send_invite(channel_id, sdp)
    
    def request_playback(self, channel_id, start_time, end_time):
        """请求回放视频"""
        self.logger.info(f"请求回放: {channel_id} {start_time} to {end_time}")
        # 伪代码：实际实现需要发送回放请求
    
    def send_alarm(self, channel_id, alarm_type, description):
        """发送报警通知"""
        self.logger.warning(f"发送报警: {alarm_type} - {description}")
        alarm_xml = XMLBuilder.alarm_notify(
            channel_id, 
            alarm_type, 
            description
        )
        self.sip_handler.send_message(alarm_xml)
    
    def _heartbeat_loop(self):
        """心跳循环"""
        while self.running:
            try:
                heartbeat_xml = XMLBuilder.heartbeat(
                    self.config['sip']['device_id']
                )
                self.sip_handler.send_message(heartbeat_xml)
            except Exception as e:
                self.logger.error(f"心跳发送失败: {str(e)}")
            
            # 按配置间隔等待
            sleep_time = self.config['sip'].get('heartbeat_interval', 60)
            for _ in range(sleep_time):
                if not self.running:
                    return
                time.sleep(1)